#include "wxyOperation.h"
#include "logger.h"
#include "wxyutils.h"
#include "OTKXString.h"
#include <vector>
#include <iterator>
#include <algorithm>
//导出
void Export(xstring dialog)
{
    {
        pfcSession_ptr Session = pfcGetProESession();
        pfcModel_ptr Model;
        pfcModels_ptr Models = pfcModels::create();
        try
        {
            uifcList_ptr list_export = uifcListFind(dialog, "list_export");
            xstringsequence_ptr ItemNames = list_export->GetItemNameArray();
            if (ItemNames)
            {
                for (int i = 0; i < ItemNames->getarraysize(); i++)
                {
                    uifcListItem_ptr ListItem = uifcListItemFind(dialog, list_export->GetComponent(), ItemNames->get(i));
                    if (ListItem->GetCheckedState() == uifcCHECK_STATE_SET)
                    {
                        Model = Session->GetModelFromFileName(ListItem->GetText());
                        Models->append(Model);
                    }
                }
            }
            if (Models->getarraysize() > 0)
            {

                uifcOptionMenu_ptr op_type = uifcOptionMenuFind(dialog, "op_type");
                xstring SelectedItemName = op_type->GetSelectedItemNameArray()->get(0);
                uifcOptionMenuItem_ptr Selected = uifcOptionMenuItemFind(dialog, "op_type", SelectedItemName);
                string ExportType = Selected->GetText();
                uifcTextArea_ptr ta_info = uifcTextAreaFind(dialog, "ta_info");
                if (ExportType == "stp")
                {
                    ta_info->SetTextValue(ta_info->GetTextValue() + "开始导出stp...\n");
                    _3D2Stp(dialog, Models);
                    ta_info->SetTextValue(ta_info->GetTextValue() + "导出完成...\n");
                }
                else if (ExportType == "pdf")
                {
                    ta_info->SetTextValue(ta_info->GetTextValue() + "开始导出pdf...\n");
                    _Drw2Pdf(dialog, Models);
                    ta_info->SetTextValue(ta_info->GetTextValue() + "导出完成!\n");
                }
                else if (ExportType == "drw")
                {
                    ta_info->SetTextValue(ta_info->GetTextValue() + " 开始导出drw...\n");
                    _MoveDrw(dialog, Models);
                    ta_info->SetTextValue(ta_info->GetTextValue() + "导出完成!\n");
                }
            }
        }
        OTK_EXCEPTION_PRINT_LOG
        catch (exception e)
        {
            LOG(LOG_ERROR) << "Msg:" << e.what();
        }
    }
}
//3d导出stp
void _3D2Stp(xstring dialog, pfcModels_ptr &Models)
{
    pfcSession_ptr Session = pfcGetProESession();
    uifcInputPanel_ptr ip_outdir = uifcInputPanelFind(dialog, "ip_outdir");
    xstring AimPath = ip_outdir->GetTextValue();
    pfcWindow_ptr CurrentWindow = Session->GetCurrentWindow();
    try
    {
        uifcOptionMenu_ptr op_type = uifcOptionMenuFind(dialog, "op_type");
        xstring SelectedItemName = op_type->GetSelectedItemNameArray()->get(0);
        uifcOptionMenuItem_ptr Selected = uifcOptionMenuItemFind(dialog, "op_type", SelectedItemName);
        string ExportType = Selected->GetText();
        uifcTextArea_ptr ta_info = uifcTextAreaFind(dialog, "ta_info");
        pfcExportInstructions_ptr Step3DExportInst = ReadStpOption(dialog);
        int mcount = Models->getarraysize();
        uifcProgressBar_ptr PsB_Export = uifcProgressBarFind(dialog, "PsB_Export");
        PsB_Export->SetMaximumIntegerValue(mcount);
        PsB_Export->SetMinimumIntegerValue(0);
        for (int i = 0; i < mcount; i++)
        {
            pfcModel_ptr Model = Models->get(i);
            xstring FullName, Filename, profilepath;
            FullName = Model->GetFullName();
            Filename = FullName + ".stp";
            Model->Export(AimPath + "\\" + Filename, Step3DExportInst);
            ta_info->SetTextValue(ta_info->GetTextValue() + FullName + ".stp----Done!\n");

            PsB_Export->SetIntegerValue(i + 1);
        }
    }
    OTK_EXCEPTION_PRINT_LOG
    catch (exception e)
    {
        LOG(LOG_ERROR) << "Msg:" << e.what();
    }
}
//drw导出为pdf
void _Drw2Pdf(xstring dialog, pfcModels_ptr &Models)
{
    uifcInputPanel_ptr ip_outdir = uifcInputPanelFind(dialog, "ip_outdir");
    xstring AimPath = ip_outdir->GetTextValue();
    pfcSession_ptr session = pfcGetProESession();
    try
    {
        uifcTextArea_ptr ta_info = uifcTextAreaFind(dialog, "ta_info");
        pfcExportInstructions_ptr ExportInst = ReadPdfOption(dialog);
        int mcount = Models->getarraysize();
        uifcProgressBar_ptr PsB_Export = uifcProgressBarFind(dialog, "PsB_Export");
        PsB_Export->SetMaximumIntegerValue(mcount);
        PsB_Export->SetMinimumIntegerValue(0);
        for (int i = 0; i < mcount; i++)
        {
            pfcModel_ptr Model = Models->get(i);
            xstring filename = AimPath + "\\" + Model->GetFullName() + ".pdf";
            Model->Display(); //导出pdf需要先显示模型
            Model->Export(filename, ExportInst);
            ta_info->SetTextValue(ta_info->GetTextValue() + Model->GetFullName() + ".pdf----Done!\n");

            PsB_Export->SetIntegerValue(i + 1);
        }
    }
    OTK_EXCEPTION_PRINT_LOG
    catch (exception e)
    {
        LOG(LOG_ERROR) << "Msg:" << e.what();
    }
}
//迁移drw到目标目录
void _MoveDrw(xstring dialog, pfcModels_ptr &Models)
{
    uifcInputPanel_ptr ip_outdir = uifcInputPanelFind(dialog, "ip_outdir");
    string AimPath = ip_outdir->GetTextValue();
    try
    {
        uifcTextArea_ptr ta_info = uifcTextAreaFind(dialog, "ta_info");
        pfcDXFExportInstructions_ptr dwginst = pfcDXFExportInstructions::Create();
        pfcExportInstructions_ptr ExportInst = (pfcExportInstructions_ptr)dwginst;
        int mcount = Models->getarraysize();
        uifcProgressBar_ptr PsB_Export = uifcProgressBarFind(dialog, "PsB_Export");
        PsB_Export->SetMaximumIntegerValue(mcount + floor(mcount * 0.1) + 1);
        PsB_Export->SetMinimumIntegerValue(0);
        for (int i = 0; i < Models->getarraysize(); i++)
        {
            pfcModel_ptr Model = Models->get(i);
            pfcModelDescriptor_ptr ModelDesc = Model->GetDescr();
            ModelDesc->SetPath(xstring(AimPath.c_str()));
            Model->Backup(ModelDesc);
            // xstring filename = AimPath + "\\" + Model->GetFullName() + ".dxf";
            // Model->Export(filename, ExportInst);
            ta_info->SetTextValue(ta_info->GetTextValue() + Model->GetFullName() + ".drw----Done!\n");
            PsB_Export->SetIntegerValue(i + 1);
        }
        uifcCheckButton_ptr ck_purge = uifcCheckButtonFind(dialog, "ck_purge");
        if (ck_purge->GetCheckedState() == uifcCHECK_STATE_SET)
        {
            MyPurge(AimPath);
        }
        PsB_Export->SetIntegerValue(mcount + floor(mcount * 0.1) + 1);
    }
    OTK_EXCEPTION_PRINT_LOG
    catch (exception e)
    {
        LOG(LOG_ERROR) << "Msg:" << e.what();
    }
}
//读取stp导出选项
pfcExportInstructions_ptr ReadStpOption(xstring handle)
{
    xstring DialogName = handle;

    pfcAssemblyConfiguration inConfigration;
    pfcGeometryFlags_ptr inGeometry;
    inGeometry = pfcGeometryFlags::Create();
    pfcSTEP3DExportInstructions_ptr StpOption;
    StpOption = pfcSTEP3DExportInstructions::Create(inConfigration, inGeometry);
    try
    {
        uifcOptionMenu_ptr op_asmas = uifcOptionMenuFind(DialogName, "op_asmas");
        string AsmConfig = op_asmas->GetSelectedItemNameArray()->get(0);
        //"flat_file" "single_file" "multi_files" "assembly_parts"
        switch (gconvert::str2int(AsmConfig))
        {
        case 0:
            StpOption->SetConfiguration(pfcEXPORT_ASM_FLAT_FILE);
            break;
        case 1:
            StpOption->SetConfiguration(pfcEXPORT_ASM_SINGLE_FILE);
            break;
        case 2:
            StpOption->SetConfiguration(pfcEXPORT_ASM_MULTI_FILES);
            break;
        case 3:
            StpOption->SetConfiguration(pfcEXPORT_ASM_ASSEMBLY_PARTS);
            break;
        default:
            StpOption->SetConfiguration(pfcAssemblyConfiguration_nil);
            break;
        }

        uifcRadioGroup_ptr rg_export = uifcRadioGroupFind(DialogName, "rg_export");
        string rg_selected = rg_export->GetSelectedItemNameArray()->get(0);
        switch (gconvert::str2int(rg_selected))
        {
        case 0:
            inGeometry->SetAsSolids(xtrue);
            break;
        case 1:
            inGeometry->SetAsQuilts(xtrue);
            break;
        case 2:
            inGeometry->SetAsSurfaces(xtrue);
            break;
        default:
            break;
        }
        StpOption->SetGeometry(inGeometry);

        pfcInclusionFlags_ptr IncludeFlag = pfcInclusionFlags::Create();
        IncludeFlag->SetIncludeDatums(uifcCheckButtonFind(DialogName, "ck_datum")->GetCheckedState());
        IncludeFlag->SetIncludeFaceted(uifcCheckButtonFind(DialogName, "ck_facet")->GetCheckedState());
        StpOption->SetIncludedEntities(IncludeFlag);
    }
    OTK_EXCEPTION_PRINT_LOG

    return (pfcExportInstructions_ptr)StpOption;
}
//读取pdf导出选项
pfcExportInstructions_ptr ReadPdfOption(xstring handle)
{
    xstring dialog = handle;
    pfcPDFOptions_ptr options = pfcPDFOptions::create();
    try
    {
        pfcPDFOption_ptr option1 = pfcPDFOption::Create();
        option1->SetOptionType(pfcPDFOPT_FONT_STROKE);
        uifcRadioGroup_ptr rg_font = uifcRadioGroupFind(dialog, "rg_font");
        string selected = rg_font->GetSelectedItemNameArray()->get(0);
        switch (gconvert::str2int(selected))
        {
        case 1:
            option1->SetOptionValue(pfcCreateIntArgValue(pfcPDF_STROKE_ALL_FONTS));
            break;
        case 2:
            option1->SetOptionValue(pfcCreateIntArgValue(pfcPDF_USE_TRUE_TYPE_FONTS));
            break;
        default:
            option1->SetOptionValue(pfcCreateIntArgValue(pfcPDFFontStrokeMode_nil));
            break;
        }
        options->append(option1);
        pfcPDFOption_ptr option2 = pfcPDFOption::Create();
        option2->SetOptionType(pfcPDFOPT_COLOR_DEPTH);
        uifcRadioGroup_ptr rg_color = uifcRadioGroupFind(dialog, "rg_color");
        selected = rg_color->GetSelectedItemNameArray()->get(0);
        switch (gconvert::str2int(selected))
        {
        case 0:
            option2->SetOptionValue(pfcCreateIntArgValue(pfcPDF_CD_COLOR));
            break;
        case 1:
            option2->SetOptionValue(pfcCreateIntArgValue(pfcPDF_CD_GRAY));
            break;
        case 2:
            option2->SetOptionValue(pfcCreateIntArgValue(pfcPDF_CD_MONO));
            break;
        default:
            option2->SetOptionValue(pfcCreateIntArgValue(pfcPDFColorDepth_nil));
            break;
        }
        options->append(option2);
        pfcPDFOption_ptr option3 = pfcPDFOption::Create();
        option3->SetOptionType(pfcPDFOPT_RASTER_DPI);
        uifcOptionMenu_ptr op_dpi = uifcOptionMenuFind(dialog, "op_dpi");
        selected = op_dpi->GetSelectedItemNameArray()->get(0);
        option3->SetOptionValue(pfcCreateIntArgValue(gconvert::str2int(selected) * 100));
        options->append(option3);
        pfcPDFOption_ptr option4 = pfcPDFOption::Create();
        option4->SetOptionType(pfcPDFOPT_LAUNCH_VIEWER);
        uifcCheckButton_ptr ck_openpdf = uifcCheckButtonFind(dialog, "ck_openpdf");
        if (ck_openpdf->GetCheckedState() == uifcCHECK_STATE_SET)
            option4->SetOptionValue(pfcCreateBoolArgValue(xtrue));
        else
            option4->SetOptionValue(pfcCreateBoolArgValue(xfalse));
        options->append(option4);
    }
    OTK_EXCEPTION_PRINT_LOG

    pfcPDFExportInstructions_ptr instructions = pfcPDFExportInstructions::Create();
    instructions->SetOptions(options);
    instructions->SetFilePath(NULL);
    instructions->SetProfilePath(NULL);
    return instructions;
}
//获取模型列表并写入list_export
void GetList(xstring dialog)
{
    pfcSession_ptr session = pfcGetProESession();
    uifcInputPanel_ptr ip_workdir = uifcInputPanelFind(dialog, "ip_workdir");
    string WorkDir = ip_workdir->GetTextValue();
    try
    {
        uifcOptionMenu_ptr op_type = uifcOptionMenuFind(dialog, "op_type");
        xstring SelectedItemName = op_type->GetSelectedItemNameArray()->get(0);
        uifcOptionMenuItem_ptr Selected = uifcOptionMenuItemFind(dialog, "op_type", SelectedItemName);
        string ExportType = Selected->GetText();
        uifcTextArea_ptr ta_info = uifcTextAreaFind(dialog, "ta_info");
        pfcModels_ptr models = pfcModels::create();
        if (ExportType == "stp")
        {
            models->insertseq(0, session->ListModelsByType(pfcMDL_ASSEMBLY));
            models->insertseq(0, session->ListModelsByType(pfcMDL_PART));
        }
        else if (ExportType == "pdf" || ExportType == "drw")
        {
            models->insertseq(0, session->ListModelsByType(pfcMDL_DRAWING));
            uifcCheckButton_ptr ck_retriworkdir = uifcCheckButtonFind(dialog, "ck_retriworkdir");
            if (ck_retriworkdir->GetCheckedState() == uifcCHECK_STATE_SET)
            {
                vector<_FileExt> files;
                ListFileByType(WorkDir.c_str(), "*.drw.*", files);
                for_each(files.begin(), files.end(), [](_FileExt i)
                         { LOG(LOG_INFO) << i.filepath + i.filename; });
                for (vector<_FileExt>::iterator it = files.begin(); it != files.end(); it++)
                {
                    string filenamenoext = (*it).filepath + (*it).filename;
                    //模型在工作区中跳过
                    if (session->GetModelFromFileName(filenamenoext.c_str()))
                        continue;
                    else
                    {
                        pfcModelDescriptor_ptr ModelDesc = pfcModelDescriptor::CreateFromFileName(filenamenoext.c_str());
                        pfcModel_ptr mdl = session->RetrieveModel(ModelDesc);
                        models->append(mdl);
                    }
                }
            }
            uifcCheckButton_ptr ck_retrisession = uifcCheckButtonFind(dialog, "ck_retrisession");
            if (ck_retrisession->GetCheckedState() == uifcCHECK_STATE_SET)
            {
                pfcModels_ptr tms = pfcModels::create();
                tms->insertseq(0, session->ListModelsByType(pfcMDL_ASSEMBLY));
                tms->insertseq(0, session->ListModelsByType(pfcMDL_PART));
                for (int i = 0; i < tms->getarraysize(); i++)
                {
                    pfcModelDescriptor_ptr ModelDesc = tms->get(i)->GetDescr();
                    xstring filename = ModelDesc->GetFullName() + ".drw";
                    if (session->GetModelFromFileName(filename))
                        continue;
                    pfcModelDescriptor_ptr ModelDesc_n = pfcModelDescriptor::CreateFromFileName(filename);
                    try
                    {
                        pfcModel_ptr mdl = session->RetrieveModel(ModelDesc_n);
                        models->append(mdl);
                    }
                    OTK_EXCEPTION_PRINT_LOG
                }
            }
        }

        uifcList_ptr list_export = uifcListFind(dialog, "list_export");
        xstringsequence_ptr list_content = list_export->GetItemNameArray();
        //清空列表
        if (list_content)
            list_export->DeleteItemsByName(list_content);

        int count = models->getarraysize();
        if (count > 0)
        {
            for (int i = 0; i < count; i++)
            {
                pfcModel_ptr model = models->get(i);
                uifcItemPositionData_ptr ItemPos = uifcItemPositionData::Create();
                ItemPos->SetIndex(i);
                ItemPos->SetIsBefore(xfalse);
                xstring istr = to_string(i).c_str();
                uifcListItem_ptr ListItem = uifcListItemDefine(istr);
                ListItem->SetText(model->GetFileName());
                ListItem->SetCheckedState(uifcCHECK_STATE_SET);
                ListItem->SetIsSelected(xtrue);
                list_export->InsertItem(ListItem, ItemPos);
            }
        }
    }
    OTK_EXCEPTION_PRINT_LOG
}
/*
//根据类型获取目录下所有文件
void ListFileByType(string path, string match, vector<_FileExt> &files)
{
    //文件句柄
    intptr_t hFile = 0;
    //文件信息
    struct _wfinddata64i32_t fileinfo; //包含中文目录，使用宽字符
    wstring p;
    wstring wpath;
    wstring wmatch;
    gconvert::utf82uni(path, wpath);
    gconvert::utf82uni("\\" + match, wmatch);

    _wfindfirst(p.assign(wpath).append(wmatch).c_str(), &fileinfo); //查找目录下文件，并将信息存入fileinfo
    if ((hFile = _wfindfirst(p.assign(wpath).append(wmatch).c_str(), &fileinfo)) != -1)
    {
        do
        {
            //排除目录
            if (wcscmp(fileinfo.name, L".") == 0 || wcscmp(fileinfo.name, L"..") == 0)
                continue;
            p.assign(wpath).append(L"\\").append(fileinfo.name);
            _FileExt file(p);
            files.push_back(file); //_FileExt自建类，包含绝对路径和扩展名
        } while (_wfindnext(hFile, &fileinfo) == 0);
        _findclose(hFile);
    }
}
*/